package com.hyt.it.ogt.kq.service.gov.service.impl;

import com.alibaba.fastjson.JSON;
import com.hyt.common.utils.result.Result;
import com.hyt.core.base.BaseEntity;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.constant.CommonConstant;
import com.hyt.it.ogt.kq.common.config.ConfigManager;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.service.gov.feign.tps.GovTpsClient;
import com.hyt.it.ogt.kq.service.gov.mapper.OfficeExamAgreementMapper;
import com.hyt.it.ogt.kq.service.gov.model.entity.OfficeExamAgreement;
import com.hyt.it.ogt.kq.service.gov.model.entity.SysFile;
import com.hyt.it.ogt.kq.service.gov.service.IOfficeExamAgreementService;
import com.hyt.it.ogt.kq.service.gov.service.ISysFileService;
import com.hyt.it.ogt.kq.service.gov.service.obs.CloudObsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 系统级与机构级考试协议表 服务实现类
 * </p>
 *
 * @author huangyh
 * @since 2021-04-06
 */
@Slf4j
@Service
public class OfficeExamAgreementServiceImpl extends BaseServiceImpl<OfficeExamAgreementMapper, OfficeExamAgreement> implements IOfficeExamAgreementService {


    @Resource
    private CloudObsService cloudObsService;
    @Resource
    private ConfigManager configManager;
    @Resource
    private ISysFileService iSysFileService;
    @Resource
    private GovTpsClient tpsClient;

    @Override
    public void initOfficeExamAgreement(String officeId) {

        Integer count = lambdaQuery()
                .eq(OfficeExamAgreement::getOfficeId, officeId)
                .eq(OfficeExamAgreement::getDelFlag, false)
                .count();

        if (count <= 0) {
            baseMapper.initOfficeExamAgreement(officeId);
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importExamNotice(MultipartFile file) throws Exception {

        String path = null;
        try {
            String code = "agreementHtml";

            path = StringUtils.join(configManager.getCloudRootPath(), TEMPLATE, "/", code, "/", file.getOriginalFilename());
            // 考试协议包上传到云存储
            String url = cloudObsService.updateFile(path, file.getInputStream());

            SysFile sysFile = new SysFile();
            sysFile.setName(file.getOriginalFilename()).setPath(path).setType(code).setUrl(url);
            iSysFileService.save(sysFile);

            //系统级数据更新
            this.lambdaUpdate()
                    .eq(OfficeExamAgreement::getType, 1)
                    .eq(OfficeExamAgreement::getLevel, 1)
                    .eq(OfficeExamAgreement::getDelFlag, false)
                    .set(OfficeExamAgreement::getContent, sysFile.getId())
                    .update();

            //机构数据为空，则赋值。
            this.lambdaUpdate()
                    .eq(OfficeExamAgreement::getType, 1)
                    .eq(OfficeExamAgreement::getLevel, 2)
                    .isNull(OfficeExamAgreement::getContent)
                    .eq(OfficeExamAgreement::getDelFlag, false)
                    .set(OfficeExamAgreement::getContent, sysFile.getId())
                    .update();


            log.info("上传考生须知模板成功，ID：{}", sysFile.getId());
        } catch (Exception e) {
            if (path != null) {
                cloudObsService.deleteFile(path);
            }
            throw e;
        }

    }

    @Override
    public List<OfficeExamAgreement> getSysDefaultAgreement() {
        List<OfficeExamAgreement> list = this.lambdaQuery()
                .eq(BaseEntity::getDelFlag, Boolean.FALSE)
                .eq(OfficeExamAgreement::getLevel, CommonConstant.ONE)
                .list();

        for (OfficeExamAgreement item : list) {
            if (item.getType() == 1) {
                if (item.getContent() != null) {
                    SysFile sysFile = iSysFileService.getById(item.getContent());
                    if (sysFile != null) {
                        String res = tpsClient.getStringFromHuaweiObs(sysFile.getPath(), UTF_8);
                        Result result = JSON.parseObject(res, Result.class);
                        if (result.getObj() != null) {
                            Document doc = Jsoup.parse(result.getObj().toString());
                            item.setContent(doc.body().html());
                        } else {
                            throw new KqException(ResponseCode.ERROR_GET_AGREEMENT_FROM_OBS.getCode(), ResponseCode.ERROR_GET_AGREEMENT_FROM_OBS.getMsg());
                        }
                    }
                }
                break;
            }
        }
        
        return list;
    }
}
